/**
 * Created by qqli on 5/27/15.
 */
'use strict';

Ctrl.controller('AppManageCtrl', ['$scope', '$http', '$rootScope', '$timeout', '$filter', 'updateSqcService', 'appService', 'ruleService', 'publishService', 'modifyService',
    function ($scope, $http, $rootScope, $timeout, $filter, AppSqc, App, Rule, Publish, Modify) {
        $rootScope.title = 'App Management';
        $rootScope.header = 'Search';
        $rootScope.path = "app_management";

        $rootScope.activeLi();

        loadStyle(HOST + "styles/build/app-manage.min.css");
        loadStyle(HOST + "bower_components/bootstrap-datetimepicker/datetimepicker.min.css");
        loadStyle(HOST + "bower_components/bootstrap-select/bootstrap-select.min.css");
        loadScript(HOST + "bower_components/bootstrap-select/bootstrap-select.min.js");

        $('footer a').html('Go to Dashboard chart').attr('href', HOST + 'admin/#/dashboard');

        // store app screen shot
        var appSs = [],
            appSs1 = null,
            appSs2 = null,
            appSs3 = null,
            appSs4 = null;
        // bind event
        $(window).resize(function () {
            resizeTable(100);
        });
        resizeTable(100);

        var $uploadAppModal = $('#upload-app'),
            $modalBodyCover = $uploadAppModal.find('.modal-body-cover'),
            $btnSubmit = $uploadAppModal.find('.btn-submit'),
            $chooseApk = $('#choose-apk'),
            $uploadApk = $('#upload-apk'),
            $apk = $('#apk'),
            $apkUrl = $('#apk-url'),
            $markStar = $uploadAppModal.find('.mark-star'),
            $uploadArea = $uploadAppModal.find('.upload-area'),
            $pagination = $('#pagination');

        $scope.sourceChannelStr = "Official Recommendation";

        //click 'upload' btn and show modal
        $scope.uploadApp = function () {
            // reset
            $scope.newApp = {
                appName: null,
                apkPackName: null,
                appSize: null,
                appStartGrade: null,
                appDeveloper: null,
                appDetail: null,
                appPermission: null,
                appIconUUID: null,
                appImgUUIDs: null,
                sourceChannel: 1,
                versionName: null,
                versionCode: null,
                appUrlUUID: null,
                appOsVersion: null,
                label: "Update",
                installFlag: 0
            };
            $('#source-channel-select').find('.choosen-value').text("Official Recommendation");
            $('#label-select').find('.choosen-value').text("Update");

            // add app don't need id, modify app need id
            if ($scope.newApp.id) {
                delete $scope.newApp.id;
            }

            appSs = [];
            appSs1 = null;
            appSs2 = null;
            appSs3 = null;
            appSs4 = null;

            $btnSubmit.attr('disabled', false).html('OK');
            $uploadApk.prop('disabled', true).html('Upload');
            $('#upload-app form')[0].reset();
            $uploadArea.find('img').attr('src', '').hide();
            $uploadAppModal.find(".modal-title").text("Upload App");

            $uploadAppModal.modal('show');
            $modalBodyCover.hide();
            $markStar.find('.fa-star').addClass('fa-star-o star').removeClass('fa-star');
            $btnSubmit.attr('id', 'save-app');

            //refresh select os/cu
            $('.select-picker').find('option').prop('selected', false).removeAttr('selected');
            $('.select-picker').selectpicker('refresh');
            DropMenuListener();
        };

        /**
         * modal, upload app
         */
        $uploadAppModal
            // click upload img area
            .on('click', '.upload-area', function () {
                $(this).find('input[type=file]').trigger('click');
            })

            .on('click', '.upload-area input[type=file]', function (e) {
                e.stopPropagation();
            })

            // click 'Path' btn, trigger input[type=file]
            .on('click', '#choose-apk', function () {
                if ($(this).hasClass('on')) {
                    $apk.trigger('click');
                } else {
                    alertModal('Uploading, Please wait');
                }
            })

            // choose apk
            .on('change', '#apk', function () {
                var file = this.files[0];
                if (!file) {
                    $apkUrl.val("");
                    $uploadApk.prop('disabled', true).html('Upload');
                    return false;
                }

                if (getSuffix(file.name) !== 'apk') {
                    alertModal('Please choose an apk file to upload');
                    return false;
                }
                if (file.size > 1024 * 1024 * 100) {
                    alertModal('apk file oversized (100MB at most)');
                    return false;
                }
                $apkUrl.val(file.name);
                $uploadApk.prop('disabled', false).html('Upload');
            })

            // apk upload
            .on('click', '#upload-apk', function () {
                var file = $apk[0].files[0];
                if (file) {
                    // can not choose another apk
                    $chooseApk.removeClass('on');

                    uploadFile({
                        modal: $("#upload-app"),
                        file: file,
                        useFormData: true,
                        fileName: 'apkFile',
                        url: HOST + 'app/res/parseApk',
                        onProgress: function (file, loaded, total) {
                            $uploadApk.prop('disabled', true).html(Math.round(loaded / total * 100) + '%');
                        },
                        onSuccess: function (file, response) {
                            $uploadApk.html('<i class="fa fa-check"></i>');
                            var data = JSON.parse(response);
                            if (data.status === 1) {
                                if (data.data.resultFlag === 2) {
                                    $scope.newApp.appUrlUUID = data.data.apkuuid;
                                    $scope.newApp.appName = data.data.appName;
                                    $scope.newApp.appSize = data.data.fileSize + '';
                                    $scope.newApp.apkPackName = data.data.packageName;
                                    $scope.newApp.appPermission = data.data.permissions;
                                    $scope.newApp.versionCode = data.data.versionCode;
                                    $scope.newApp.versionName = data.data.versionName;
                                    $scope.newApp.appIconUUID = data.data.iconUuid;
                                    $('#app-icon-preview').attr('src', data.data.icon).fadeIn();

                                    $scope.$digest();
                                } else if (data.data.resultFlag === 1) {
                                    alertModal('Apk parse failed');
                                    $uploadApk.prop('disabled', false).html('Upload');

                                } else if (data.data.resultFlag === 3) {
                                    alertModal('The same pkg of apk already exists.');
                                    $uploadApk.prop('disabled', false).html('Upload');

                                } else {
                                    alertModal('Apk upload failed');
                                    $uploadApk.prop('disabled', false).html('Upload');
                                }
                            }
                            $chooseApk.addClass('on');
                        },
                        onFailure: function (file, response) {
                            alertModal('Parse file failed');
                            $uploadApk.prop('disabled', false).html('Upload');
                            $chooseApk.addClass('on');
                        },
                        onComplete: function () {
                            $apk.val('');
                            $chooseApk.addClass('on');
                        },
                        onAbort: function () {
                            $apk.val('');
                            $chooseApk.addClass('on');
                            $uploadApk.prop('disabled', false).html('Upload');
                        }
                    });
                } else {
                    alertModal('Please choose an apk first');
                }
            })

            // icon upload
            .on('change', '#app-icon', function () {
                var file = this.files[0];
                if (!isImage(file.name)) {
                    alertModal('Please choose jpg/png/gif to upload');
                    return false;
                }
                if (file.size > 1024 * 800) {
                    alertModal('app icon file oversized (800KB at most)');
                    return false;
                }
                imageReader(file, function (result) {
                    $('#app-icon-preview').attr('src', result).fadeIn();
                });
                uploadFile({
                    file: file,
                    useFormData: true,
                    fileName: 'iconFile',
                    url: HOST + 'app/res/uploadIcon',
                    onProgress: function (file, loaded, total) {
                        // $(this).parent().find('.cover').css({
                        //     'top': (-Math.round(loaded / total * 100) + '%'),
                        //     'z-index': 12
                        // });
                    },
                    onSuccess: function (file, response) {
                        var data = JSON.parse(response);
                        if (data.status === 1) {
                            if (data.data.result === 'success') {
                                $scope.newApp.appIconUUID = data.data.fileUuid;
                            } else {
                                alertModal('Image upload failed');
                            }
                        }
                    },
                    onFailure: function (file, response) {
                        alertModal('Parse file failed');
                    },
                    onComplete: function () {
                    }
                });
            })

            // screen shot upload
            .on('change', '.app-ss', function () {
                var self = this;
                var file = this.files[0];
                if (!isImage(file.name)) {
                    alertModal('Please choose jpg/png/gif to upload');
                    return false;
                }
                if (file.size > 1024 * 300) {
                    alertModal('app screenshot file oversized (300KB at most)');
                    return false;
                }
                imageReader(file, function (result) {
                    $(self).parent().find('.app-ss-preview').attr('src', result).fadeIn();
                });
                uploadFile({
                    file: file,
                    useFormData: true,
                    fileName: 'imgFile',
                    url: HOST + 'app/res/uploadImg',
                    onProgress: function (file, loaded, total) {
                        // $(this).parent().find('.cover').css({
                        //     'top': (-Math.round(loaded / total * 100) + '%'),
                        //     'z-index': 12
                        // });
                    },
                    onSuccess: function (file, response) {
                        var data = JSON.parse(response);
                        if (data.status === 1) {
                            if (data.data.result === 'success') {
                                if ($(self).attr('id') === 'app-ss-1') {
                                    appSs1 = data.data.fileUuid;
                                } else if ($(self).attr('id') === 'app-ss-2') {
                                    appSs2 = data.data.fileUuid;
                                } else if ($(self).attr('id') === 'app-ss-3') {
                                    appSs3 = data.data.fileUuid;
                                } else if ($(self).attr('id') === 'app-ss-4') {
                                    appSs4 = data.data.fileUuid;
                                }
                            } else {
                                alertModal('Image upload failed');
                            }
                        }
                    },
                    onFailure: function (file, response) {
                        alertModal('Parse file failed');
                    },
                    onComplete: function () {
                    }
                });
            })

            // click to delete upload img or icon
            .on('click', '.icon-delete', function () {
                var $this = $(this);
                var uploadFileId = $this.prev().find('input').attr('id');
                $this.prev().find('img').attr('src', '').fadeOut();

                switch (uploadFileId) {
                    case 'app-icon':
                        $scope.newApp.appIconUUID = '';
                        break;
                    case 'app-ss-1':
                        appSs1 = '';
                        break;
                    case 'app-ss-2':
                        appSs2 = '';
                        break;
                    case 'app-ss-3':
                        appSs3 = '';
                        break;
                    case 'app-ss-4':
                        appSs4 = '';
                        break;
                }
                $this.fadeOut();
            })

            // modify app
            .on('click', '#modify-save-app', function () {
                $scope.addApp("modify", $scope.newApp.id);
            })

            // add app
            .on('click', '#save-app', function () {
                $scope.addApp("add");
            });

        $scope.addApp = function (operate, appId) {
            var ssArr = [appSs1, appSs2, appSs3, appSs4];
            appSs = [];
            for (var i = 0; i < ssArr.length; i++) {
                if (ssArr[i]) {
                    appSs.push(ssArr[i]);
                }
            }
            $scope.newApp.appImgUUIDs = appSs.join(',');

            // check select os and select cu
            var osVal = $('#select-os-v').next().find('button .filter-option').text();
            if (osVal === 'Please Select') {
                $scope.newApp.appOsVersion = '';
                alertModal('Please select Os Version');
                return false;
            } else {
                $scope.newApp.appOsVersion = osVal;
            }

            // validation
            //console.log($scope.newApp);
            for (var a in $scope.newApp) {
                if (!$.trim($scope.newApp[a]) && (a != 'appStartGrade') && (a != 'appPermission')) {
                    alertModal('All informations needed, please check again');
                    return false;
                }
            }

            if ($scope.newApp.appName.length > 64) {
                alertModal('App name should not more than 64 characters');
                return false;
            }
            if ($scope.newApp.appDeveloper.length > 64) {
                alertModal('App developer should not more than 64 characters');
                return false;
            }
            if ($scope.newApp.appDetail.length > 1024) {
                alertModal('App details should not more than 1024 characters');
                return false;
            }

            $btnSubmit.prop('disabled', true).html('Uploading...');
            $modalBodyCover.show();

            if (operate === "add") {
                App.save($scope.newApp).$promise.then(function (data) {
                    if (data.status === 1) {
                        alertModal('Upload Success');
                        $uploadAppModal.modal('hide');
                        $scope.queryApp();

                    } else if (data.status === -1) {
                        lozLogin();

                    } else {
                        alertModal('App upload failed');
                        $modalBodyCover.hide();
                        $btnSubmit.html('OK').attr('disabled', false);
                    }
                });
            } else if (operate === "modify") {
                $scope.newApp.id = appId;
                Modify.save($scope.newApp).$promise.then(function (data) {
                    if (data.status === 1) {
                        $uploadAppModal.modal('hide');
                        alertModal('Modify Success');
                        $scope.queryApp();

                    } else if (data.status === 2) {
                        $uploadAppModal.modal('hide');
                        alertModal("Can not upload other pkg apk");

                    } else if (data.status === -1) {
                        lozLogin();

                    } else {
                        alertModal('App Modify failed');
                        $modalBodyCover.hide();
                        $btnSubmit.html('OK').attr('disabled', false);
                    }
                });
            }
        };

        // set query model
        // params for url
        $scope.fixParams = {
            pageNo: 1
        };
        $scope.queryParams = {
            appName: $scope.appName,
            appCuReference: $scope.appCuReference,
            sourceChannel: $scope.sourceChannel,
            releaseStatus: $scope.releaseStatus,
            label: $scope.label,
            trash: 0
        };

        $scope.orderProp = "appSequence";

        $scope.queryApp = function (pageNo) {
            //pageNo: for click  search btn
            if (pageNo) {
                $scope.fixParams.pageNo = pageNo;
            }

            $http.post(HOST + 'app/res/list/' + $scope.fixParams.pageNo, $scope.queryParams)
                .success(function (data) {
                    if (data.status === 1) {
                        var _data = data.data;
                        $scope.apps = _data.appList;
                        $(".chk-all").removeClass('checked');

                        /**
                         * total page
                         * pagination(): make pagination
                         * jumpToPage(): input and turn to page
                         * @type {number}
                         */
                        var totalPage = Math.ceil(_data.total / _data.pageSize);
                            if (totalPage <= 1) {
                                $pagination.html('');
                                return false;
                        }

                        pagination($pagination, _data.pageNo, totalPage, _data.total);
                        jumpToPage($pagination, totalPage, function (i) {
                            $scope.fixParams.pageNo = i;
                            $scope.queryApp();
                        });
                    } else if (data.status === -1) {
                        lozLogin();
                    }
                });
            return false;
        };

        $scope.queryOs = function () {
            $http.get(HOST + 'os/list/').success(function (data) {
                if (data.status === 1) {
                    $scope.osList = data.data;

                } else if (data.status === -1) {
                    lozLogin();
                }
            });
        };

        $scope.updateSqc = function (event) {
            var elem = $(event.currentTarget),
                appId = +elem.attr('data-id'),
                sequence = elem.val();
            if ($.trim(sequence) === '') {
                elem.val(elem.attr('data-val'));
                return false;
            }
            sequence = +sequence;
            if (typeof(sequence) === 'number' && !isNaN(sequence)) {
                if (sequence >= 0 && sequence <= 9999) {
                    var saveParams = {
                        appId: appId,
                        sequence: sequence
                    };
                    AppSqc.save(saveParams).$promise.then(function (data) {
                        if (data.status > 0) {
                            for (var i = 0; i < $scope.apps.length; i++) {
                                if ($scope.apps[i].id === appId) {
                                    $scope.apps[i].appSequence = sequence;
                                }
                            }
                        } else if (data.status === -1) {
                            lozLogin();

                        } else {
                            alertModal('Update app sequence failed!');
                        }
                    });
                } else {
                    alertModal('Sequence out of range: 0-9999');
                    elem.val(elem.attr('data-val'));
                    return false;
                }
            } else {
                alertModal('Sequence should be an integer');
                elem.val(elem.attr('data-val'));
                return false;
            }
        };

        $scope.rule = {
            id: null,
            upgradePeriod: null,
            autoDownwifi: null,
            delUpgradeapk: null,
            clearCache: null
        };

        // upgrade rule
        $scope.showUpgrade = function () {
            Rule.query().$promise.then(function (data) {
                $scope.rule = data.data;
            });
            $('#upgrade-rule').modal('show');
        };

        // save rule
        $scope.saveRule = function () {
            Rule.save($scope.rule).$promise.then(function (data) {
                if (data.status > 0) {
                    // alertModal('Rule upgrade success');
                    $('#upgrade-rule').modal('hide');
                } else if (data.status === -1) {
                    lozLogin();

                } else {
                    alertModal('Rule upgrade failed');
                }
            });
        };

        // delete app
        $scope.deleteApp = function () {
            var ids = getTableCheckedId($('.tbody table'));
            if (!ids.length) {
                alertModal("Please choose app to delete");
                return;
            }
            function deleteAppRequest() {
                $("#confirmModal").modal("hide");

                App.remove(ids).$promise.then(function (data) {
                    if (data.status === 1) {
                        $scope.queryApp(1);
                    } else if (data.status === 0) {
                        alertModal("Delete failure");

                    } else if (data.status === 605) {
                        alertModal("Have app has released, can not delete");

                    } else if (data.status === -1) {
                        lozLogin();
                    }
                });
            }

            var text = 'Do you really want to delete choosen apps?';
            confirmModal(text, deleteAppRequest);
        };

        function removeAppFromScope(ids) {
            var toDelete = [],
                indexOffset = 0;
            $.each($scope.apps, function (index) {
                if ($.inArray(this.id, ids) !== -1) {
                    toDelete.push(index);
                }
            });
            for (var i = 0; i < toDelete.length; i++) {
                $scope.apps.splice(toDelete[i] - indexOffset, 1);
                indexOffset++;
            }
        }

        /**
         * pagination
         * click and turn to page
         */
        $pagination.on('click', '.goto', function () {
            $scope.fixParams.pageNo = $(this).data('page');
            $scope.queryApp();

            return false;
        });

        function DisplayInfo() {
            var jqShowInfo = $('#show-info');
            this.jqModal = jqShowInfo;
        }


        /*show info*/
        $scope.showInfo=function(event){
            $scope.parseDate=function(date){
                var date = new Date(date);
                var Y = date.getFullYear() + '-';
                var M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
                var D = date.getDate() + ' ';
                var h = date.getHours() + ':';
                var m = date.getMinutes() + ':';
                var s = date.getSeconds();
                var str=Y+M+D;
                return str;
            };
            var elem = $(event.currentTarget),
                appId = +elem.attr('data-id');

           var  $pagination=$('#sub-pagination');
            var infoParam={
                pageNo:1
            }

            $scope.queryInfo=function(pageNom){
                if(pageNom){
                    infoParam.pageNo=pageNom
                }
                /*HOST+'views/testData/info.json/'+appId+'/'+infoParam.pageNo*/
                $http.get(HOST+'operlog/get/'+appId+'/'+infoParam.pageNo).success(function(data) {
                    $scope.infos = data.data;
                    var _data=data.data;
                    var totalPage = Math.ceil(_data.total / _data.pageSize);
                    if (totalPage <= 1) {
                        $pagination.html('');
                        return false;
                    }

                    pagination($pagination, _data.pageNo, totalPage, _data.total);
                    jumpToPage($pagination, totalPage, function (i) {
                        infoParam.pageNo = i;
                        $scope.queryInfo();
                    });


                });

            };
          /*  $http.get(HOST+'views/testData/info.json').success(function(data) {
             $scope.infos = data.data;
             });*/
            $scope.queryInfo();
            $scope.displayInfo = new DisplayInfo();
            $scope.displayInfo.jqModal.modal('show');
            $pagination.off('click', '.goto');
            $pagination.on('click', '.goto', function () {
                infoParam.pageNo = $(this).data('page');
                $scope.queryInfo();
                return false;
            });




        };

        /**
         * modify app
         */
        $scope.modifyApp = function (event) {
            var elem = $(event.currentTarget),
                appId = +elem.attr('data-id');

            $scope.modify = {
                appId: appId
            };

            Modify.query($scope.modify).$promise.then(function (data) {
                // reset
                var _data = data.data;
                $scope.newApp = {
                    id: _data.id,
                    appName: _data.appName,
                    apkPackName: _data.apkPackName,
                    appSize: _data.appSize,
                    appStartGrade: _data.appStartGrade,
                    appDeveloper: _data.appDeveloper,
                    appDetail: _data.appDetail,
                    appPermission: _data.appPermission,
                    appIconUUID: _data.appIcon,
                    appImgUUIDs: _data.appImgs,
                    sourceChannel: _data.sourceChannel,
                    versionName: _data.versionName,
                    versionCode: _data.versionCode,
                    appUrlUUID: _data.appUrl,
                    appOsVersion: _data.appOsVersion,
                    label: _data.label,
                    installFlag: _data.installFlag
                };

                $apkUrl.val($scope.newApp.appUrlUUID);
                $('#source-channel-select').find('.choosen-value').text(_data.sourceChannelStr);
                $('#label-select').find('.choosen-value').text(_data.label);

                if (_data.appImgs == null) {
                    appSs = _data.appImgs;
                } else {
                    appSs = _data.appImgs.split(',');
                    appSs1 = appSs[0];
                    appSs2 = appSs[1];
                    appSs3 = appSs[2];
                    appSs4 = appSs[3];
                }

                //reset img src null
                $('#app-ss-2').parent().find('img').attr('src', '').fadeOut();
                $('#app-ss-3').parent().find('img').attr('src', '').fadeOut();
                $('#app-ss-4').parent().find('img').attr('src', '').fadeOut();

                $('#app-icon').parent().find('img').attr('src', _data.appIcon).fadeIn();
                $('#app-ss-1').parent().find('img').attr('src', appSs1).fadeIn();

                if (appSs2) {
                    $('#app-ss-2').parent().find('img').attr('src', appSs2).fadeIn();
                }
                if (appSs3) {
                    $('#app-ss-3').parent().find('img').attr('src', appSs3).fadeIn();
                }
                if (appSs4) {
                    $('#app-ss-4').parent().find('img').attr('src', appSs4).fadeIn();
                }

                $markStar.find('.fa:lt(' + (_data.appStartGrade) + ')').addClass('fa-star').removeClass('fa-star-o star');
                $markStar.find('.fa:gt(' + (_data.appStartGrade - 1) + ')').addClass('fa-star-o star').removeClass('fa-star');

                $('.select-picker').selectpicker('deselectAll');
                DropMenuListener();

                // set select multiple
                var osArr = _data.appOsVersion.split(',');
                //cuArr = _data.appCuReference.split(',');

                // set select option
                function setSelectOption($select, $lis, arr) {
                    var $options = $select.find('option'),
                        arrLen = arr.length,
                        optionLen = $options.length;

                    if ((optionLen - 1) === arrLen) {
                        $lis.eq(0).trigger('click');
                    } else {
                        for (var i = 0; i < arrLen; i++) {
                            for (var j = 0; j < optionLen; j++) {
                                if ($.trim($options.eq(j).val()) == $.trim(arr[i])) {
                                    $options.eq(j).prop('selected', true).attr('selected', 'selected');
                                    break;
                                }
                            }
                        }
                        $select.selectpicker('refresh');
                    }
                }

                setSelectOption($('#select-os-v'), $('#select-os-wrap ul li'), osArr);
                //setSelectOption($('#select-cu'), $('#select-cu-wrap ul li'), cuArr);

                $btnSubmit.attr('id', 'modify-save-app');

                $apk.val('');
                $uploadApk.prop("disabled", true).html('Upload');
                $btnSubmit.attr('disabled', false).html('OK');
                $uploadAppModal.find(".modal-title").text("Edit App");
                $uploadAppModal.modal('show');
                $modalBodyCover.hide();

                DropMenuListener();
            });
            return false;
        };


        function DropMenuListener() {
            var selectedIdentify = 'selected';
            $('ul.selectpicker  li').off('click');
            $('ul.selectpicker  li').on('click', function () {
                var _$this = $(this),
                    currIndex = _$this.index(),
                    $select = _$this.parents('.bootstrap-select').prev('select'),
                    $selectWrap = _$this.parents('td');

                // select all
                if (currIndex === 0 && !_$this.hasClass(selectedIdentify)) {
                    $select.selectpicker('innerSelectAll');
                    _$this.addClass("selected");
                    return false;

                } else if (currIndex === 0 && _$this.hasClass(selectedIdentify)) {
                    // de select all
                    $select.selectpicker('deselectAll');
                    return false;
                } else {
                    var $firstLi = $selectWrap.find('ul li').eq(0);
                    var liLen = $selectWrap.find('li').length;
                    var selectedLen = $selectWrap.find('li.selected').length;

                    // select all by click li but not select all li
                    if ((liLen - 2) === selectedLen && !_$this.hasClass('selected')) {
                        $firstLi.addClass(selectedIdentify);
                    } else {
                        $firstLi.removeClass(selectedIdentify);
                    }
                }
            });
        }

        // function publish app
        function PublishApp() {
        }

        PublishApp.prototype = {
            resetModal: function () {
                this.jqModal.find(".autoSearch").val("");
                $scope.publishData.curefs = [];
                $scope.statusFlag.cuCheckAll = false;
                $scope.statusFlag.productCheckAll = false;
                $scope.statusFlag.isDelete = true;
                $scope.publishData.searchCu = '';
                $scope.publishData.searchProduct = '';
            },
            setCheckAllStatus: function ($box) {
                $timeout(function () {
                    var jqCheckbox = $box.find(".chk-item"),
                        checkboxLen = jqCheckbox.length,
                        checkboxCheckedLen = jqCheckbox.filter(function () {
                            return $(this).hasClass("checked") ? $(this) : "";
                        }).length,

                        jqCheckboxVisible = $box.find(".checkbox:visible"),
                        visibleLen = jqCheckboxVisible.length,
                        visibleCheckedLen = jqCheckboxVisible.find(".chk-item").filter(function () {
                            return $(this).hasClass("checked") ? $(this) : "";
                        }).length;

                    if ((checkboxCheckedLen < checkboxLen && visibleLen === checkboxLen) ||
                        (visibleCheckedLen < visibleLen) ||
                        visibleLen === 0) {
                        if ($box.hasClass("cu-ref")) {
                            $scope.statusFlag.cuCheckAll = false;
                        } else {
                            $scope.statusFlag.productCheckAll = false;
                        }
                    } else {
                        if ($box.hasClass("cu-ref")) {
                            $scope.statusFlag.cuCheckAll = true;
                        } else {
                            $scope.statusFlag.productCheckAll = true;
                        }
                    }
                });
            },
            initProductData: function (data) {
                for (var i = 0; i < data.length; i++) {
                    var _data = data[i];
                    _data.checkStatus = false;
                    _data.curefArr = [];

                    for (var j = 0; j < _data.curefs.length; j++) {
                        var obj = {
                            "cu": _data.curefs[j],
                            "checkStatus": false
                        };
                        _data.curefArr.push(obj);
                    }
                }
                return data;
            },
            getProductFilter: function () {
                $timeout(function () {
                    $scope.publishData.filterProducts = $filter('filter')(
                        $scope.publishData.products,
                        {product: $scope.publishData.searchProduct}
                    );
                });
            },
            getCuFilter: function () {
                $timeout(function () {
                    $scope.publishData.filterCurefs = $filter('filter')(
                        $scope.publishData.curefs,
                        {cu: $scope.publishData.searchCu}
                    );
                });
            },
            chkAllProductData: function () {
                $timeout(function () {
                    var data = $scope.publishData.products;
                    var filterData = $scope.publishData.filterProducts;

                    for (var i in filterData) {
                        for (var j in data) {
                            if (filterData[i].product == data[j].product) {
                                data[j].checkStatus = true;

                                // set all cu checked
                                for (var o in data[j].curefArr) {
                                    data[j].curefArr[o].checkStatus = true;
                                }
                            }
                        }
                    }

                    $scope.statusFlag.cuCheckAll = true;
                });
            },
            chkNoneProductData: function () {
                $timeout(function () {
                    var data = $scope.publishData.products;
                    var filterData = $scope.publishData.filterProducts;

                    for (var i in filterData) {
                        for (var j in data) {
                            if (filterData[i].product == data[j].product) {
                                data[j].checkStatus = false;

                                // set all cu checked
                                for (var o in data[j].curefArr) {
                                    data[j].curefArr[o].checkStatus = false;
                                }
                            }
                        }
                    }

                    $scope.statusFlag.cuCheckAll = false;
                });
            },
            showCu: function (productName) {
                $timeout(function () {
                    var data = $scope.publishData.products;

                    for (var i = 0; i < data.length; i++) {
                        if (data[i].product == productName) {
                            $scope.publishData.curefs = [].concat(data[i].curefArr);
                            break;
                        }
                    }
                });
            },
            clickProductToSetCuChecked: function (productName) {
                var data = $scope.publishData.products,
                    productTrueCount = 0;

                // set cu
                for (var i = 0; i < data.length; i++) {
                    if (data[i].product == productName) {
                        data[i].checkStatus = true;
                        for (var j = 0; j < data[i].curefArr.length; j++) {
                            data[i].curefArr[j].checkStatus = true;
                        }
                        break;
                    }
                }

                $scope.statusFlag.cuCheckAll = true;

                // set product check all
                for (var i = 0; i < data.length; i++) {
                    if (data[i].checkStatus === true) {
                        productTrueCount += 1;
                    }
                }

                if (productTrueCount == data.length) {
                    $scope.statusFlag.productCheckAll = true;
                }
            },
            clickProductToSetCuUnChecked: function (productName) {
                var data = $scope.publishData.products;

                for (var i = 0; i < data.length; i++) {
                    if (data[i].product == productName) {
                        data[i].checkStatus = false;
                        for (var j = 0; j < data[i].curefArr.length; j++) {
                            data[i].curefArr[j].checkStatus = false;
                        }
                        break;
                    }
                }
                $scope.statusFlag.productCheckAll = false;
                $scope.statusFlag.cuCheckAll = false;
            },
            clickCuToSetCuChecked: function (cuName) {
                $timeout(function () {
                    var data = $scope.publishData.products;

                    for (var i = 0; i < data.length; i++) {
                        var _data = data[i],
                            curefLen = _data.curefArr.length;

                        for (var j = 0; j < curefLen; j++) {
                            if (_data.curefArr[j].cu == cuName) {

                                //if cu checked, then product checked
                                _data.checkStatus = true;
                                _data.curefArr[j].checkStatus = true;

                                $scope.publishApp.setCheckAllStatus($scope.publishApp.jqProduct);
                                $scope.publishApp.setCheckAllStatus($scope.publishApp.jqCuRef);

                                // if all cu status is false, the product status is false
                                /*var trueStatusCount = 0;
                                 for (var o = 0; o < curefLen; o++) {
                                 if (_data.curefArr[o].checkStatus == true) {
                                 trueStatusCount += 1;
                                 }
                                 }

                                 if (trueStatusCount == curefLen) {
                                 $scope.statusFlag.cuCheckAll = true;
                                 }*/

                                break;
                            }
                        }
                    }
                });
            },
            clickCuToSetCuUnChecked: function (cuName) {
                $timeout(function () {
                    var data = $scope.publishData.products;

                    for (var i = 0; i < data.length; i++) {
                        var _data = data[i],
                            curefLen = _data.curefArr.length;

                        for (var j = 0; j < curefLen; j++) {
                            if (_data.curefArr[j].cu == cuName) {
                                _data.curefArr[j].checkStatus = false;

                                // count cu status
                                var falseStatusCount = 0;
                                for (var o = 0; o < curefLen; o++) {
                                    if (_data.curefArr[o].checkStatus == false) {
                                        falseStatusCount += 1;
                                    }
                                }

                                // if all cu status is false, the product status is false
                                if (falseStatusCount == curefLen) {
                                    _data.checkStatus = false;
                                    $scope.statusFlag.productCheckAll = false;
                                } else {
                                    $scope.statusFlag.cuCheckAll = false;
                                }

                                break;
                            }
                        }
                    }
                });
            },
            clickCuAllToSetCuChecked: function (productName) {
                $timeout(function () {
                    var data = $scope.publishData.products,
                        filterData = $scope.publishData.filterCurefs,
                        productTrueCount = 0;

                    // set cu
                    for (var i = 0; i < data.length; i++) {
                        if (data[i].product == productName) {
                            data[i].checkStatus = true;

                            for (var j in data[i].curefArr) {
                                for (var o in filterData) {
                                    if (data[i].curefArr[j].cu == filterData[o].cu) {
                                        data[i].curefArr[j].checkStatus = true;
                                    }
                                }
                            }
                            break;
                        }
                    }

                    $scope.publishApp.setCheckAllStatus($scope.publishApp.jqProduct);
                    $scope.publishApp.setCheckAllStatus($scope.publishApp.jqCuRef);

                    //$scope.statusFlag.cuCheckAll = true;

                    // set product check all
                    /*for (var i = 0; i < data.length; i++) {
                     if (data[i].checkStatus === true) {
                     productTrueCount += 1;
                     }
                     }

                     if (productTrueCount == data.length) {
                     $scope.statusFlag.productCheckAll = true;
                     }*/
                });
            },
            clickCuAllToSetCuUnChecked: function (productName) {
                $timeout(function () {
                    var data = $scope.publishData.products,
                        filterData = $scope.publishData.filterCurefs,
                        cuFalseCount = 0;

                    // set cu
                    for (var i = 0; i < data.length; i++) {
                        var _data = data[i];
                        if (_data.product == productName) {
                            for (var j in _data.curefArr) {
                                for (var o in filterData) {
                                    if (_data.curefArr[j].cu == filterData[o].cu) {
                                        _data.curefArr[j].checkStatus = false;
                                    }
                                }
                            }

                            // set product check all
                            for (var i = 0; i < _data.curefArr.length; i++) {
                                if (_data.curefArr[i].checkStatus === false) {
                                    cuFalseCount += 1;
                                }
                            }

                            if (cuFalseCount == _data.curefArr.length) {
                                _data.checkStatus = false;
                                $scope.statusFlag.productCheckAll = false;
                            }

                            break;
                        }
                    }
                    $scope.statusFlag.cuCheckAll = false;
                });
            },
            clickUndeleteSetAllUncheck: function () {
                $timeout(function () {
                    var data = $scope.publishData.products;

                    for (var i in data) {
                        data[i].checkStatus = false;

                        // set all cu checked
                        for (var j in data[i].curefArr) {
                            data[i].curefArr[j].checkStatus = false;
                        }
                    }
                });
            },
            showChkbox: function () {
                $timeout(function () {
                    $("#published-cu").find(".chk-item").removeClass("hidden");
                    $("#published-cu").find(".chk-all").removeClass("hidden");
                    $scope.statusFlag.isDelete = false;
                });
            },
            hideChkbox: function () {
                $timeout(function () {
                    $("#published-cu").find(".chk-item").removeClass("checked").addClass("hidden");
                    $("#published-cu").find(".chk-all").addClass("hidden");
                    $scope.statusFlag = {
                        cuCheckAll: false,
                        productCheckAll: false,
                        isDelete: true
                    };
                    $scope.publishApp.clickUndeleteSetAllUncheck();
                });
            }
        };

        $scope.publishParam = {
            appIds: [],
            curefs: []
        };
        $scope.publishData = {
            searchProduct: "",
            searchCu: "",
            products: [],
            curefs: [],
            filterProducts: [],
            filterCurefs: []
        };
        $scope.statusFlag = {
            cuCheckAll: false,
            productCheckAll: false,
            isDelete: true
        };
        $scope.deleteCus = {
            storePublishedAppId: "",
            deleteCusBtnText: "Delete",
            undeleteCusBtnText: "Undelete"
        };

        function PublishCus() {
            var jqPublishApp = $('#publish-app');
            this.jqModal = jqPublishApp;
            this.jqProduct = jqPublishApp.find(".product");
            this.jqCuRef = jqPublishApp.find(".cu-ref");
            this.jqModalBodyCover = jqPublishApp.find(".modal-body-cover");
        }

        PublishCus.prototype = PublishApp.prototype;

        // click publish btn
        $scope.showPublish = function () {
            var ids = getTableCheckedId($('.tbody table'));
            if (!ids.length) {
                alertModal('Please choose app to publish');
                return;
            }

            //判断已选app是否完整，因为存在app来自其他cms上传，只得到部份信息
            var a,
                validItemArr = ["appName", "label", "sourceChannel", "appDeveloper", "appOsVersion",
                    "appDetail", "appIcon", "appImgs"];

            for (a = 0; a < ids.length; a++) {
                //findLastIndex和_.findIndex类似，但反向迭代数组，当predicate通过真检查时，最接近末端的索引值将被返回。
                var index = _.findLastIndex($scope.apps, {"id": ids[a]});

                if (index !== -1) {
                    var item = $scope.apps[index];
                    var keys = _.map(item, function (val, key) {
                        if (val === null) {
                            return key;
                        }
                    });

                    var lastKeys = (_.without(keys, 'appStartGrade')).sort();
                    var intersectionArr = _.intersection(validItemArr, lastKeys); //intersection获取交集
                    if (intersectionArr.length > 0) {
                        alertModal("Certain application information is not complete, Please check.");
                        return false;
                    }
                }
            }

            //开始发布
            $scope.publishApp = new PublishCus();
            $scope.publishParam.appIds = ids;
            $scope.publishApp.resetModal();

            Publish.query().$promise.then(function (data) {
                $scope.publishData.products = $scope.publishApp.initProductData(data.data);
            });

            $scope.publishApp.jqModal.modal('show');
        };

        // search input on change
        $scope.iptSearchProductChange = function () {
            $scope.publishApp.setCheckAllStatus($scope.publishApp.jqProduct);
        };
        $scope.iptSearchCuChange = function () {
            $scope.publishApp.setCheckAllStatus($scope.publishApp.jqCuRef);
        };

        // submit publish app
        $scope.savePublish = function (e) {
            var jqThis = $(e.currentTarget),
                cusArr = [];

            var data = $scope.publishData.products;
            for (var i = 0; i < data.length; i++) {
                for (var j = 0; j < data[i].curefArr.length; j++) {
                    if (data[i].curefArr[j].checkStatus == true) {
                        cusArr.push(data[i].curefArr[j].cu);
                    }
                }
            }
            if (cusArr.length === 0) {
                alertModal("Please select CU Ref");
                return false;
            }

            $scope.publishParam.curefs = cusArr;

            jqThis.html('Publishing...').attr('disabled', true);
            $scope.publishApp.jqModalBodyCover.show();

            $http.post(HOST + 'app/publish', $scope.publishParam)
                .success(function (data) {
                    if (data.status > 0) {
                        alertModal(data.msg ||　'publish success');
                        $scope.publishApp.jqModal.modal("hide");

                        $scope.queryApp();
                        jqThis.html('Ok').attr('disabled', false);
                        $scope.publishApp.jqModalBodyCover.hide();
                    } else if (data.status === -1) {
                        lozLogin();

                    } else {
                        alertModal(data.msg ||　'publish failed');

                        jqThis.html('Ok').attr('disabled', false);
                        $scope.publishApp.jqModalBodyCover.hide();
                    }
                });
        };

        function PublishedCus() {
            var jqPublishedCu = $('#published-cu');
            this.jqModal = jqPublishedCu;
            this.jqProduct = jqPublishedCu.find(".product");
            this.jqCuRef = jqPublishedCu.find(".cu-ref");
            this.jqDeleteBtn = jqPublishedCu.find(".btn-delete");
            this.jqModalBodyCover = jqPublishedCu.find(".modal-body-cover");
        }

        PublishedCus.prototype = PublishApp.prototype;

        // view publish product and cu ref
        $scope.showPublishedCu = function (e) {
            $scope.publishApp = new PublishedCus();

            $scope.publishApp.jqDeleteBtn.text($scope.deleteCus.deleteCusBtnText);

            var jqThis = $(e.currentTarget),
                releaseStatus = jqThis.data("status");

            $scope.deleteCus.storePublishedAppId = jqThis.data("id");

            if (releaseStatus == 0) {
                return false;
            }

            $scope.publishApp.resetModal();

            Publish.queryPublished({
                appId: $scope.deleteCus.storePublishedAppId
            }).$promise.then(function (data) {
                    $scope.publishData.products = $scope.publishApp.initProductData(data.data);
                });

            $scope.publishApp.jqModal.modal('show');

            return false;
        };

        // click delete btn
        $scope.deleteCusBtn = function (e) {
            var jqThis = $(e.currentTarget);

            if ($scope.statusFlag.isDelete === true) {
                $scope.publishApp.showChkbox();
                jqThis.text($scope.deleteCus.undeleteCusBtnText);
            } else {
                $scope.publishApp.hideChkbox();
                jqThis.text($scope.deleteCus.deleteCusBtnText);
            }
        };

        // submit delete cus
        $scope.saveDeleteCu = function (e) {
            var jqThis = $(e.currentTarget),
                cusArr = [];

            // if not in delete status, hide modal and return
            if ($scope.statusFlag.isDelete === true) {
                $scope.publishApp.jqModal.modal("hide");
                return false;
            }

            var data = $scope.publishData.products;
            for (var i = 0; i < data.length; i++) {
                for (var j = 0; j < data[i].curefArr.length; j++) {
                    if (data[i].curefArr[j].checkStatus == true) {
                        cusArr.push(data[i].curefArr[j].cu);
                    }
                }
            }

            if (cusArr.length === 0) {
                alertModal("Please select CU Ref");
                return false;
            }

            jqThis.html('Deleting...').attr('disabled', true);
            $scope.publishApp.jqModalBodyCover.show();

            $http.post(HOST + 'app/curefs/del/' + $scope.deleteCus.storePublishedAppId, cusArr)
                .success(function (data) {
                    if (data.status > 0) {
                        alertModal('Delete success');
                        $scope.publishApp.jqModal.modal("hide");

                        $scope.queryApp();
                        jqThis.html('Ok').attr('disabled', false);
                        $scope.publishApp.jqModalBodyCover.hide();
                    } else if (data.status === -1) {
                        lozLogin();

                    } else {
                        alertModal('Delete failed');

                        jqThis.html('Ok').attr('disabled', false);
                        $scope.publishApp.jqModalBodyCover.hide();
                    }
                });
        };

        // un publish
        $scope.showUnpublish = function () {
            var ids = getTableCheckedId($('.tbody table'));
            if (!ids.length) {
                alertModal('Please choose app to unpublish');
                return;
            }

            function unpublishRequest() {
                $("#confirmModal").modal("hide");

                $http.post(HOST + 'app/unPublish', ids)
                    .success(function (data) {
                        if (data.status > 0) {
                            $scope.queryApp();
                            //alertModal('unPublish success');

                        } else if (data.status === -1) {
                            lozLogin();
                        } else {
                            alertModal('unPublish failed');
                        }
                    });
            }

            var text = "These apps will be unpublished, do you want to continue?";
            confirmModal(text, unpublishRequest);
        };

        // init
        $scope.queryApp();
        $scope.queryOs();

        $(function () {
            /**
             * init select mutiple
             */
            $('.select-picker').selectpicker({
                'noneSelectedText': 'Please Select'
            });
        });

    }]);